<?php

namespace app\admin\controller\user;

use app\admin\model\cms\AlbumModel;
use app\admin\model\cms\Live;
use app\admin\model\cms\LiveCategoryModel;
use app\admin\model\cms\MembershipExpiryRecordModel;
use app\admin\model\cms\OrderModel;
use app\admin\model\cms\Plate;
use app\admin\model\cms\Platepost;
use app\admin\model\cms\Video;
use app\admin\model\cms\VideoCategoryModel;
use app\admin\model\UserGroup;
use app\api\service\HuaWeiSMS;
use app\common\controller\Backend;
use app\common\library\Auth;
use app\common\library\Sms as Smslib;
use app\common\model\Config;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\helper\ArrayHelper;
use think\Hook;
use think\Model;

/**
 * 会员申请管理
 *
 * @icon fa fa-user
 */
class MembershipApplication extends Backend
{

    protected $relationSearch = true;
    protected $searchFields = 'id,username,nickname,mobile';//表单搜索框允许检索的字段

    /**
     * @var \app\admin\model\User
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('User');
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $where_data = $this->request->param('filter', '');
            if ($where_data) {
                $where_data = json_decode($where_data, true);
            }
            $list = OrderModel::whereIn('pay_type', [3, 4])->whereIn('is_ratify', [0,1]);
            if (!empty($where_data['user_nickname'])) {
                $user_ids = \app\admin\model\User::where('nickname', 'like', "%{$where_data['user_nickname']}%")->column('id');
                if ($user_ids) {
                    $list = $list->whereIn('user_id', $user_ids);//用户id
                }
            }
            if (!empty($where_data['goods_type_name'])) {
                $list = $list->where('goods_type', $where_data['goods_type_name']);//商品类型
            }
            if (!empty($where_data['price'])) {
                $list = $list->where('price', $where_data['price']);//订单应付金额
            }

            if (!empty($where_data['pay_status']) || ($where_data['pay_status'] ?? null) === '0') {
                if (in_array($where_data['pay_status'], [0, 1])) {
                    $list = $list->where('pay_status', $where_data['pay_status']);//审核是否通过
                }
            }
            $list = $list->with('user')
                ->order('createtime', $order)
                ->paginate($limit);
            foreach ($list as $v) {
                if (!$v['user']) {
                    $v['user'] = \app\admin\model\User::getSoftDeleteUser($v['user_id']);
                }
            }
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        Db::startTrans();
        if (!$params['goods_type'] || !$params['table_name'] || !$params['goods_id'] || !$params['user_id']) {
            $this->error('缺少参数');
        }
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            //$result = $this->model->allowField(true)->save($params);

            $result = $this->addMembershipLog($params['user_id'], $params['goods_type'], $params['table_name'], $params['goods_id']);
            Db::commit();
        } catch (ValidateException | PDOException | Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = OrderModel::where('id', $ids)->with('user')->find();
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $row['user'] = \app\admin\model\User::getSoftDeleteUser($row['user_id']);
        if ($this->request->isPost()) {
            $pay_status = input('row.pay_status') ?? 0;
            $user = Db::name('user')->find($row['user_id']);
            if ($pay_status == 1) {
                $obj = new OrderModel();
                //支付临时申请订单
                $res = $obj->payOrder_3($ids, $user, $pay_status);
                if ($res['code'] != 200) {
                    $this->error($res['msg']);
                }
                //$sm_msg = "您的{$row['goods_type_name']}-{$row['goods_name']}-15天权限申请审核通过";
                $state_msg = '通过';
            } else {
                OrderModel::where('id', $ids)->update(['is_ratify' => 1]);//是否完成申请单|默认0:否,1:admin操作完成,这值只有pay_type=3时,admin在后台选择完是否通过后才会进行赋值成1
                //$sm_msg = "您的{$row['goods_type_name']}-{$row['goods_name']}-15天权限申请审核被驳回";
                $state_msg = '被驳回';
            }
            //发送短信提示
//            if (!Hook::get('sms_send')) {
//                $this->error(__('请在后台插件管理安装短信验证插件'));
//            }

            //$ret = Smslib::notice($user['mobile'], $sm_msg);
            $obj = new HuaWeiSMS();
            $ret = $obj->send($user['mobile'], ["{$row['goods_type_name']}-{$row['goods_name']}", $state_msg], '开通提示类');
            if ($ret['code'] != 200) {
                $this->error('发送失败，请检查短信配置是否正确');
            }
            $this->success();
        }
        $this->view->assign('row', $row);
        return $this->view->fetch();
    }

    //根据订单商品类型动态获取相关商品来源
    public function getGoodsList()
    {
        $goods_type = $this->request->param('goods_type', '');
        $table_name = $this->request->param('table_name', '');
        if (!$goods_type || !$table_name) {
            $this->error('缺少参数');
        }
        switch ($goods_type) {
            case 'categories':
                $data = $this->getCategoryModel($table_name);
                break;
            case 'articles':
                $data = $this->getArticlesModel($table_name);
                break;
            case 'user_group':
                $data = UserGroup::where('is_charge', 1)
                    ->where('membership_price', '>', 0)
                    ->select();
                break;
            case 'album':
                $data = AlbumModel::where('membership_price', '>', 0)->select();
                break;
            default:
                $this->error('类型错误');
        }
        if (!$data) {
            $this->error('当前分类下没有付费内容');
        }
        return $this->success('', '', $data);
    }

    //获取栏目分类model
    private function getCategoryModel($table_name)
    {
        switch ($table_name) {
            case 'video_category':
                $model = new VideoCategoryModel();//视频
                break;
            case 'plate':
                $model = new Plate();//论坛分类
                break;
            case 'live_category':
                $model = new LiveCategoryModel();//直播分类
                break;
            default:
                return false;
        }
        $data = $model->where('membership_price', '>', 0)->select();
        if (!count($data)) {
            return false;
        }

        foreach ($data as $k => $v) {
            $res[] = [
                'id' => $v['id'],
                'name' => $v['platename'],
                'membership_price' => $v['membership_price'],
            ];
        }
        return $res;
    }

    //获取内容
    private function getArticlesModel($table_name)
    {
        switch ($table_name) {
            case 'plate_post':
                $model = new Platepost();//论坛内容
                break;
            case 'live':
                $model = new Live();//直播内容
                break;
            case 'video':
                $model = new Video();//视频内容
                break;
            default:
                return false;
        }
        $data = $model->where('membership_price', '>', 0)->select();
        if (!count($data)) {
            return false;
        }

        foreach ($data as $k => $v) {
            $res[] = [
                'id' => $v['id'],
                'name' => $v['title'],
                'membership_price' => $v['membership_price'],
            ];
        }
        return $res;
    }

    //创建会员记录
    private function addMembershipLog($user_id, $goods_type, $table_name, $goods_id)
    {
        $time = time();
        $rand = rand(111, 999);
        try {
            //插入订单
            $order = OrderModel::create([
                'user_id' => $user_id,
                'goods_type' => $goods_type,
                'table_name' => $table_name,
                'goods_id' => $goods_id,
                'order_num' => "{$time}{$rand}{$user_id}",
                'pay_type' => 4,
                'price' => 0,//订单应付金额
                'membership_duration' => 15,//所购买的会员时长(天)
                'pay_status' => 1,//订单支付状态|默认0:未支付,1:已支付
                'pay_time' => date('Y-m-d H:i:s'),//用户付款时间
                'is_ratify' => 1,//是否完成申请单|默认0:否,1:admin操作完成,这值只有pay_type=3时,admin在后台选择完是否通过后才会进行赋值成1
            ]);

            $user = \app\admin\model\User::find($user_id);
            //是会员就更新用户表
            if ($goods_type == 'user_group') {
                $user_group = UserGroup::where('id', $goods_id)->find();
                //判断会员分组的有效时长 0:无限天
                if ($user_group['membership_expiry'] == 0) {
                    $period_of_validity = 1;//有效期|1=长期有效,0=无效,毫秒时间戳=有效时间
                } else {
                    $days = $user_group['membership_expiry']; // 指定的天数
                    //看当前会员是否过期 1=长期有效,0=无效,毫秒时间戳=有效时间
                    if ($user['period_of_validity'] > 1 || !$user['period_of_validity']) {
                        if ($user['period_of_validity'] < time()) {
                            $user['period_of_validity'] = 0;//毫秒
                        }
                        // 计算指定天数后的时间戳 秒
                        $specifiedTimestamp = strtotime("+{$days} days", ($user['period_of_validity'] / 1000) > 0 ?: $time) * 1000;//毫秒

                        $period_of_validity = $user['period_of_validity'] + $specifiedTimestamp;//单位毫秒
                    } elseif ($user['period_of_validity'] == 1) {
                        $period_of_validity = 1;//会员有效期(到期时间)|1=长期有效,0=无效,毫秒时间戳=有效时间
                    }
                }

                $user_success = \app\admin\model\User::where('id', $user_id)->update([
                    'group_id' => $goods_id,//会员组别id
                    'member_type' => 'member',//会员类型|tourist=游客,TrialMember=试用会员，member=正式会员'
                    'member_make_time' => time(),//会员开通时间
                    'period_of_validity' => $period_of_validity,//会员有效期(到期时间)|1=长期有效,0=无效,毫秒时间戳(13位)=有效时间
                ]);
                if (!$user_success) {
                    throw new Exception('操作失败1');
                    //dd("{user表id={$order['user_id']}微信回调成功,但更应用户信息失败" , 'error');//记录日志
                }
            } else {
                //其他就更新会员到期记录表 购买分类/文章内容
                $membership_Expiry_record_model = MembershipExpiryRecordModel::where('user_id', $user_id)
                    ->where('goods_type', $goods_type)
                    ->where('table_name', $table_name)
                    ->where('goods_id', $goods_id)
                    ->order('id', 'desc')
                    ->find();
                //判断之前是否购买过
                $expiration_time = 0;//剩余时长|没买过就默认为0
                if ($membership_Expiry_record_model) {
                    //是,时间叠加
                    $expiration_time = $membership_Expiry_record_model['expiration_time'] - $time;
                    if ($expiration_time <= 0) {
                        $expiration_time = 0;
                    }
                }
                //获取订单所购买的会员时长(天)|0:无限天
                $old_membership_duration = $order['membership_duration'] ?? 0;
                if ($order['membership_duration']) {
                    $old_membership_duration = $order['membership_duration'] * 24 * 60 * 60 + $time;
                }
//                创建
                $data_2 = [
                    'user_id' => $user_id,
                    'order_id' => $order['id'],
                    'goods_type' => $order['goods_type'],
                    'table_name' => $order['table_name'],
                    'goods_id' => $order['goods_id'],
                    'membership_duration' => $order['membership_duration'],
                    'expiration_time' => $expiration_time + $old_membership_duration,
                ];
                $success_2 = MembershipExpiryRecordModel::create($data_2);//创建会员过期记录表,查询数据的时候每次获取最后一条
                if (!$success_2) {
                    throw new Exception('操作失败2');
                    //dd("{membership_expiry_record表order_id={$order['id']}在微信支付成功回调中创建失败" , 'error');//记录日志
                }
            }
        } catch (\Exception $exception) {
            // 更新异常，抛出异常
            throw new Exception('更新会员信息失败');
        }
    }

}
